<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;


/**
 * 线上大赛投票模型
 * Class ArticleModel
 * @package app\common\model
 */
class ContestActivityVote extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;

    protected $table = 'contest_activity_vote';


    /**
     * 获取今日投票次数
     * @param $user_id  用户id
     * @param $con_id  大赛id
     * @param $works_id  作品id
     * @param $date  日期
     */
    public function getVoteNumber($user_id = null, $con_id = null, $works_id = null, $date = null)
    {
        return $this->where(function ($query) use ($user_id, $con_id, $works_id, $date) {
            if ($user_id) {
                $query->where('user_id', $user_id);
            }
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
            if ($works_id) {
                $query->where('works_id', $works_id);
            }
            if ($date) {
                $query->where('date', $date);
            }
        })->count();
    }

    /**
     * 获取用户已投票数量
     * @param $vote_way  投票方式   1  总票数方式   2 每日投票方式 3 不支持投票功能
     * @param $user_id  用户id
     * @param $con_id  大赛id
     * @param $works_id  作品id
     */
    public function userVoteNum($vote_way, $user_id = null, $con_id = null, $works_id = null)
    {
        if ($vote_way == 1) {
            $user_vote_num = $this->getVoteNumber($user_id, $con_id, $works_id); //用户投票数量
        } elseif ($vote_way == 2)  {
            $user_vote_num = $this->getVoteNumber($user_id, $con_id, $works_id, date('Y-m-d')); //用户投票数量
        }else {
            $user_vote_num = 0; //不支持点赞功能
        }
        return $user_vote_num;
    }




    /**
     * 获取用户可投票数量和文案
     * @param $vote_way  投票方式   1  总票数方式   2 每日投票方式
     * @param $user_id  用户id
     * @param $con_id  大赛id
     * @param $number  作品可投票数量
     */
    public function getVoteNum($vote_way, $number, $user_id = null, $con_id = null)
    {
        if (empty($user_id)) {
            $vote_msg = ''; //获取活动状态
            $vote_number = 0; //可投票量
        } elseif ($vote_way == 1) {
            $vote_msg = '当前可投票数'; //获取活动状态
            $have_number = $this->getVoteNumber($user_id, $con_id); //已投票量
            $vote_number = $number - $have_number; //可投票量
        } elseif ($vote_way == 2) {
            $vote_msg = '今日可投票数'; //获取活动状态
            $have_number = $this->getVoteNumber($user_id, $con_id, null, date('Y-m-d')); //已投票量
            $vote_number = $number - $have_number; //可投票量
        } else {
            $vote_msg = '此活动暂未开启投票功能'; //获取活动状态
            $vote_number = 0; //可投票量
        }

        $vote_number = $vote_number <= 0 ? 0 : $vote_number;

        return [$vote_msg, $vote_number];
    }
}
